#include <ctime>
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <vector>
using namespace std;

mutex chopstics[5];

void phd(int num, int seed) {
    srand(seed);
    while (1) {
        if (num == 4) {
            this_thread::sleep_for(chrono::seconds(rand() % 2));
            chopstics[(num + 1) % 5].lock();
            printf("phd %d get %d\n", num, (num + 1) % 5);
            this_thread::sleep_for(chrono::seconds(rand() % 2));
            chopstics[num].lock();
            printf("phd %d get %d and start to eat.\n", num, num);
            this_thread::sleep_for(chrono::seconds(0));
            chopstics[(num + 1) % 5].unlock();
            printf("phd %d put %d\n", num, (num + 1) % 5);
            chopstics[num].unlock();
            printf("phd %d put %d and start to think.\n", num, num);
        } else {
            this_thread::sleep_for(chrono::seconds(rand() % 2));
            chopstics[num].lock();
            printf("phd %d get %d\n", num, num);
            this_thread::sleep_for(chrono::seconds(rand() % 2));
            chopstics[(num + 1) % 5].lock();
            printf("phd %d get %d and start to eat.\n", num, (num + 1) % 5);
            this_thread::sleep_for(chrono::seconds(0));
            chopstics[num].unlock();
            printf("phd %d put %d\n", num, num);
            chopstics[(num + 1) % 5].unlock();
            printf("phd %d put %d and start to think.\n", num, (num + 1) % 5);
        }
    }
}

int main() {
    srand(time(0));
    vector<thread> thrds;
    for (int i = 0; i < 5; i++) { thrds.emplace_back(thread(phd, i, rand() % 100)); }
    for (auto& it : thrds) it.join();
    return 0;
}